//
//  SWPhotosDetailCollectionCell.swift
//  ChildStory
//
//  Created by linhan on 2016/11/22.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWPhotosDetailCollectionCell: UICollectionViewCell,SWALPhotoDelegate
{
    weak var photo:SWALPhoto? {
        didSet {
            photo?.delegate = self
            if _inited && _change
            {
                layoutSubviews()
            }
            
            var options = SWALPhotoRequestOptions()
            options.targetSize = bounds.size.multiply(UIScreen.main.scale)
            photo?.fetchOriginImage({ [weak self] result in
                if let image = result?.image
                {
                    //trace("image:", image.size)
                    self?._thumbImageView.image = image
                }
            }, options: options)
            
        }
    }
    weak var delegate:CollectionViewCellDelegate?
    
    private var _change:Bool = true
    
    private var _inited:Bool = false
    
    private var _thumbImageView:UIImageView = UIImageView()
    
    
    override init(frame: CGRect)
    {
        super.init(frame: frame)
        setup()
    }
    
    deinit
    {
        //trace("DEINIT SWAssetCollectionCell")
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setup()
    {
        contentView.backgroundColor = UIColor.white
        
        let Grid:CGFloat = 10
        _thumbImageView.frame = CGRectMake(0, 0, self.width - Grid, self.height)
        _thumbImageView.contentMode = .scaleAspectFill
        _thumbImageView.clipsToBounds = true
        contentView.addSubview(_thumbImageView)
        
        let longPressGesture:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressed))
        contentView.addGestureRecognizer(longPressGesture)
        
        _inited = true
    }
    
    override func prepareForReuse()
    {
        super.prepareForReuse()
        _change = true
    }
    
    func photoThumbChanged(_ photo:SWALPhoto, thumb:UIImage)
    {
        print("photoThumbChanged:", thumb.size, thumb.scale)
        _thumbImageView.image = thumb
    }
    
    override func layoutSubviews()
    {
        super.layoutSubviews()
        
        if let photo = photo , _change
        {
            _change = false
            _thumbImageView.image = nil
            if let thumb = photo.thumbnail
            {
                _thumbImageView.image = thumb
            }
        }
    }
    
    @objc private func longPressed()
    {
        delegate?.collectionViewCell(self, click: CallbackAction.LongPress, argument: nil)
    }
    
    
}
